// EasyBuy 工具函数库

/**
 * 防抖函数
 * @param {Function} func 需要防抖的函数
 * @param {number} wait 等待时间
 * @param {boolean} immediate 是否立即执行
 */
export function debounce(func, wait, immediate) {
  let timeout
  return function executedFunction(...args) {
    const later = () => {
      timeout = null
      if (!immediate) func(...args)
    }
    const callNow = immediate && !timeout
    clearTimeout(timeout)
    timeout = setTimeout(later, wait)
    if (callNow) func(...args)
  }
}

/**
 * 节流函数
 * @param {Function} func 需要节流的函数
 * @param {number} limit 时间间隔
 */
export function throttle(func, limit) {
  let inThrottle
  return function(...args) {
    if (!inThrottle) {
      func.apply(this, args)
      inThrottle = true
      setTimeout(() => inThrottle = false, limit)
    }
  }
}

/**
 * 格式化价格
 * @param {number} price 价格
 * @param {string} currency 货币符号
 */
export function formatPrice(price, currency = '￥') {
  if (typeof price !== 'number') return price
  return `${currency}${price.toFixed(2)}`
}

/**
 * 格式化时间
 * @param {Date|string|number} date 时间
 * @param {string} format 格式
 */
export function formatDate(date, format = 'YYYY-MM-DD HH:mm:ss') {
  const d = new Date(date)
  const year = d.getFullYear()
  const month = String(d.getMonth() + 1).padStart(2, '0')
  const day = String(d.getDate()).padStart(2, '0')
  const hours = String(d.getHours()).padStart(2, '0')
  const minutes = String(d.getMinutes()).padStart(2, '0')
  const seconds = String(d.getSeconds()).padStart(2, '0')
  
  return format
    .replace('YYYY', year)
    .replace('MM', month)
    .replace('DD', day)
    .replace('HH', hours)
    .replace('mm', minutes)
    .replace('ss', seconds)
}

/**
 * 深拷贝对象
 * @param {any} obj 要拷贝的对象
 */
export function deepClone(obj) {
  if (obj === null || typeof obj !== 'object') return obj
  if (obj instanceof Date) return new Date(obj.getTime())
  if (obj instanceof Array) return obj.map(item => deepClone(item))
  if (typeof obj === 'object') {
    const copy = {}
    Object.keys(obj).forEach(key => {
      copy[key] = deepClone(obj[key])
    })
    return copy
  }
}

/**
 * 获取URL参数
 * @param {string} name 参数名
 */
export function getUrlParam(name) {
  const reg = new RegExp('(^|&)' + name + '=([^&]*)(&|$)')
  const r = window.location.search.substr(1).match(reg)
  if (r != null) return decodeURIComponent(r[2])
  return null
}

/**
 * 设置本地存储
 * @param {string} key 键名
 * @param {any} value 值
 * @param {number} expire 过期时间（秒）
 */
export function setLocalStorage(key, value, expire = null) {
  const data = {
    value,
    expire: expire ? Date.now() + expire * 1000 : null
  }
  localStorage.setItem(key, JSON.stringify(data))
}

/**
 * 获取本地存储
 * @param {string} key 键名
 */
export function getLocalStorage(key) {
  try {
    const data = JSON.parse(localStorage.getItem(key))
    if (!data) return null
    
    if (data.expire && Date.now() > data.expire) {
      localStorage.removeItem(key)
      return null
    }
    
    return data.value
  } catch (e) {
    return null
  }
}

/**
 * 移除本地存储
 * @param {string} key 键名
 */
export function removeLocalStorage(key) {
  localStorage.removeItem(key)
}

/**
 * 验证邮箱格式
 * @param {string} email 邮箱地址
 */
export function validateEmail(email) {
  const re = /^[^\s@]+@[^\s@]+\.[^\s@]+$/
  return re.test(email)
}

/**
 * 验证手机号格式
 * @param {string} phone 手机号
 */
export function validatePhone(phone) {
  const re = /^1[3-9]\d{9}$/
  return re.test(phone)
}

/**
 * 生成随机字符串
 * @param {number} length 长度
 */
export function generateRandomString(length = 8) {
  const chars = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789'
  let result = ''
  for (let i = 0; i < length; i++) {
    result += chars.charAt(Math.floor(Math.random() * chars.length))
  }
  return result
}